<?php
/**
 * Piwik - Open source web analytics
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 * @version $Id: Auth.php 3565 2011-01-03 05:49:45Z matt $
 *
 * @category Piwik_Plugins
 * @package Piwik_LoginLdap
 */

require_once PIWIK_INCLUDE_PATH . '/plugins/LoginLdap/GigatecLdap.php';

/**
 *
 * @package Piwik_LoginLdap
 */
class Piwik_LoginLdap_Auth implements Piwik_Auth
{
	protected $login = null;
	protected $password = null;
	protected $token_auth = null;

	/**
	 * Authentication module's name, e.g., "Login"
	 *
	 * @return string
	 */
	public function getName()
	{
		return 'LoginLdap';
	}

	/**
	 * Authenticates user
	 *
	 * @return Piwik_Auth_Result
	 */
	public function authenticate()
	{
		$rootLogin = Zend_Registry::get('config')->superuser->login;
		$rootPassword = Zend_Registry::get('config')->superuser->password;
		$rootToken = Piwik_UsersManager_API::getInstance()->getTokenAuth($rootLogin, $rootPassword);
		try {
			$kerberosEnabled = Zend_Registry::get('config')->LoginLdap->kerberos;
		} catch (Exception $ex) {
			$kerberosEnabled = false;
		}

		if($kerberosEnabled && isset($_SERVER['REMOTE_USER']))
		{
			$kerbLogin = $_SERVER['REMOTE_USER'];
			$this->login = preg_replace('/@.*/', '', $kerbLogin);
			$this->password = '';
		} 
		
		if(is_null($this->login))
		{
			if($this->token_auth === $rootToken)
			{
				return new Piwik_Auth_Result(Piwik_Auth_Result::SUCCESS_SUPERUSER_AUTH_CODE, $rootLogin, $this->token_auth );
			}

			$login = Piwik_FetchOne(
					'SELECT login
					FROM '.Piwik_Common::prefixTable('user').' 
					WHERE token_auth = ?',
					array($this->token_auth)
			);
			if(!empty($login))
			{
				return new Piwik_Auth_Result(Piwik_Auth_Result::SUCCESS, $login, $this->token_auth );
			}
		}
		else if(!empty($this->login))
		{
			$ldapException = null;
			try {
				if($this->authenticateLDAP($this->login, $this->password, $kerberosEnabled))
				{
					return new Piwik_Auth_Result(Piwik_Auth_Result::SUCCESS, $this->login, $this->token_auth );
				}
			} catch (Exception $ex) {
				$ldapException = $ex;
			}
			
			if($this->login === $rootLogin
				&& ($this->getHashTokenAuth($rootLogin, $rootToken) === $this->token_auth)
				|| $rootToken === $this->token_auth)
			{
				$this->setTokenAuth($rootToken);
				return new Piwik_Auth_Result(Piwik_Auth_Result::SUCCESS_SUPERUSER_AUTH_CODE, $rootLogin, $this->token_auth );
			}

			$login = $this->login;
			$userToken = Piwik_FetchOne(
					'SELECT token_auth
					FROM '.Piwik_Common::prefixTable('user').' 
					WHERE login = ?',
					array($login)
			);
			if(!empty($userToken)
				&& (($this->getHashTokenAuth($login, $userToken) === $this->token_auth)
				|| $userToken === $this->token_auth))
			{
				$this->setTokenAuth($userToken);
				return new Piwik_Auth_Result(Piwik_Auth_Result::SUCCESS, $login, $userToken );
			}
			
			if (!is_null($ldapException)) {
				throw $ldapException;
			}
		}

		return new Piwik_Auth_Result( Piwik_Auth_Result::FAILURE, $this->login, $this->token_auth );
	}

	/**
	 * Accessor to set login name
	 *
	 * @param string $login user login
	 */
	public function setLogin($login)
	{
		$this->login = $login;
	}
	
	/**	
	 * Accessor to set password
	 *
	 * @param string $password password
	 */
	public function setPassword($password)
	{
		$this->password = $password;
	}

	/**
	 * Accessor to set authentication token
	 *
	 * @param string $token_auth authentication token
	 */
	public function setTokenAuth($token_auth)
	{
		$this->token_auth = $token_auth;
	}

	/**
	 * Accessor to compute the hashed authentication token
	 *
	 * @param string $login user login
	 * @param string $token_auth authentication token
	 * @return string hashed authentication token
	 */
	public function getHashTokenAuth($login, $token_auth)
	{
		return md5($login . $token_auth);
	}
	
	/**
	 * This method is used for LDAP authentication.
	 */
	private function authenticateLDAP($usr,$pwd,$sso)
	{
		try {
			$serverUrl = Zend_Registry::get('config')->LoginLdap->serverUrl;
			$baseDn = Zend_Registry::get('config')->LoginLdap->baseDn;
			$uidField = Zend_Registry::get('config')->LoginLdap->userIdField;
			$usernameSuffix = Zend_Registry::get('config')->LoginLdap->usernameSuffix;
			$adminUser = Zend_Registry::get('config')->LoginLdap->adminUser;
			$adminPass = Zend_Registry::get('config')->LoginLdap->adminPass;
			$memberOf = Zend_Registry::get('config')->LoginLdap->memberOf;
			$filter = Zend_Registry::get('config')->LoginLdap->filter;
			$kerberos = Zend_Registry::get('config')->LoginLdap->kerberos;
		} catch (Exception $e) {
			return false;
		}

		$ldap = new GigatecLdap();
		$ldap->setServerUrl($serverUrl);
		$ldap->setBaseDn($baseDn);
		$ldap->setUserIdField($uidField);
		$ldap->setUsernameSuffix($usernameSuffix);
		$ldap->setAdminUser($adminUser);
		$ldap->setAdminPass($adminPass);
		$ldap->setMemberOf($memberOf);
		$ldap->setFilter($filter);
		$ldap->setKerberos($kerberos);
		
		if ($sso == true && empty($pwd) && strtolower($kerberos) == "true") {
			if ($ldap->kerbthenticate($usr))
			{
				$db = Zend_Registry::get('db');

				$user = Piwik_FetchRow('SELECT *
					FROM '.Piwik_Common::prefixTable('user').' 
					WHERE login = ?', array($usr));

				$success = false;
				if(!empty($user))
				{
					$success = true;
					$this->token_auth = $user['token_auth'];
				}

				return $success;
			}
		} 
		else 
		{
			if ($ldap->authenticate($usr, base64_decode(str_rot13(base64_decode($pwd)))))
			{
				$db = Zend_Registry::get('db');

				$user = Piwik_FetchRow('SELECT *
					FROM '.Piwik_Common::prefixTable('user').' 
					WHERE login = ?', array($this->login));

				$success = false;
				if(!empty($user))
				{
					$success = true;
					$this->token_auth = $user['token_auth'];
				}

				return $success;
			}
		}
	}
}
